package ph.com.gs3.formalistics.fragments.views;

import ph.com.gs3.formalistics.R;
import ph.com.gs3.formalistics.model.valueobjects.application.Document;
import ph.com.gs3.formalistics.model.valueobjects.application.Form;
import ph.com.gs3.formalistics.model.valueobjects.application.FormField;
import ph.com.gs3.formalistics.utilities.DocumentViewDataExtractor;
import ph.com.gs3.formalistics.utilities.FLLogger;
import ph.com.gs3.formalistics.utilities.FieldBuilder;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

public class DocumentViewFragment extends Fragment {

	public static String TAG = DocumentViewFragment.class.getSimpleName();

	private LinearLayout llFieldsContainer;
	private Form form;
	private Document document;

	public static DocumentViewFragment createInstance(Form form, Document document) {

		DocumentViewFragment instance = new DocumentViewFragment();
		instance.form = form;
		instance.document = document;

		return instance;

	}

	// required constructor without parameters
	public DocumentViewFragment() {}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_document, container, false);

		llFieldsContainer = (LinearLayout) rootView.findViewById(R.id.Document_llFieldsContainer);

		FieldBuilder builder = new FieldBuilder(getActivity());

		for (FormField field : form.getFields()) {

			View fieldView = builder.createField(field);
			if (fieldView != null) {
				llFieldsContainer.addView(fieldView);
			} else {
				FLLogger.d(TAG, "Unable to create field for " + field.getId()
				        + ", it's probably unsupported");
			}

		}

		return rootView;
	}

	public Document updateDocumentValuesFromView() {

		if (document == null) {
			document = new Document();
			document.setWebId("0");
			document.setFormWebId(form.getWebId());
		}

		DocumentViewDataExtractor extractor = new DocumentViewDataExtractor();

		document.setFields(extractor.extract(llFieldsContainer));

		return document;

	}

}
